import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.List;

public class Test {
    Document document = null;

    public void start(){
        SAXReader reader = new SAXReader();
        try {
            document = reader.read(this.getClass().getResourceAsStream("/XML2/phone7.xml"));
        } catch (DocumentException e) {
            e.printStackTrace();
        }

    }

    public void show(){
        Element root = document.getRootElement();
        List<Element> elements = root.elements();
        for (Element element : elements) {
            String id = element.attributeValue("id");
            System.out.println(id+":");
            String trim1 = element.element("name").getText();
            String trim2 = element.element("age").getText();
            System.out.println("\t"+"name:"+trim1+"\t"+"age:"+trim2);
        }
    }
    public void add(){
        Element root = document.getRootElement();
        Element id = root.addElement("student");
        id.addAttribute("id","1006");
        Element name = id.addElement("name");
        name.setText("张三");
        Element age = id.addElement("age");
        age.setText("18");
    }
    public void remove(){
        Element root = document.getRootElement();
        List<Element> elements = root.elements();
        for (Element element : elements) {
            if(element.attributeValue("id").equals("1003")){
                element.getParent().remove(element);
            }
        }

    }
    public static void main(String[] args) {
        Test test = new Test();
        test.start();
        test.show();
        System.out.println("------------");
        test.add();
        test.show();
        System.out.println("----------");
        test.remove();
        test.show();
    }
}
